package com.bsc.rtc.lib.libraries.RetrofitNet.download;

import android.content.res.AssetManager;
import android.util.Log;

import androidx.annotation.NonNull;

import com.bsc.rtc.lib.libraries.MyApplication;
import com.bsc.rtc.lib.libraries.RetrofitNet.api.HttpsUtils;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executors;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DownloadUtil {
    public static void download(String url, final String path, final DownloadListener downloadListener) {
        AssetManager am = MyApplication.getInstance().getAssets();
        try {
            InputStream ins = am.open("log.cer");
            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, new InputStream[]{ins});
            OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    if (s.equals("119.3.8.171")
                    ) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }).addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                            .addHeader("Connection", "keep-alive")
                            .addHeader("Accept", "*/*")
                            //  .addHeader("token", MMKV.defaultMMKV().decodeString("token",""))
                            .addHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTU2OTk5NjczOCwidXNlcm5hbWUiOiIxNTIxMDExMTAxNCJ9.4rrei9jF9ksAvmWI_0-qb1EDGxvz0eqycqJpcWHi-C0")
                            .build();
                    Log.e("http", request.toString());
                    return chain.proceed(request);

                }
            })

                    .build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://119.3.8.171:8080/")
                    .client(client)
                    //通过线程池获取一个线程，指定callback在子线程中运行。
                    .callbackExecutor(Executors.newSingleThreadExecutor())
                    .build();

            DownloadService service = retrofit.create(DownloadService.class);

            Call<ResponseBody> call = service.download(url);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                    //将Response写入到从磁盘中，详见下面分析
                    //注意，这个方法是运行在子线程中的
                    writeResponseToDisk(path, response, downloadListener);
                }

                @Override
                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
                    downloadListener.onFail("网络错误～" + throwable.getMessage());
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeResponseToDisk(String path, Response<ResponseBody> response, DownloadListener downloadListener) {
        //从response获取输入流以及总大小
        writeFileFromIS(new File(path), response.body().byteStream(), response.body().contentLength(), downloadListener);
    }

    private static int sBufferSize = 8192;

    //将输入流写入文件
    private static void writeFileFromIS(File file, InputStream is, long totalLength, DownloadListener downloadListener) {
        //开始下载
        downloadListener.onStart();

        //创建文件
        if (!file.exists()) {
            if (!file.getParentFile().exists())
                file.getParentFile().mkdir();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                downloadListener.onFail("createNewFile IOException");
            }
        }

        OutputStream os = null;
        long currentLength = 0;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            byte data[] = new byte[sBufferSize];
            int len;
            while ((len = is.read(data, 0, sBufferSize)) != -1) {
                os.write(data, 0, len);
                currentLength += len;
                //计算当前下载进度
                downloadListener.onProgress((int) (100 * currentLength / totalLength));
            }
            //下载完成，并返回保存的文件路径
            downloadListener.onFinish(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            downloadListener.onFail("IOException");
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
